package utils

import play.api.libs.json.Json
import implicits.Implicits._
import org.apache.commons.io.FileUtils
import shapeless.ops.hlist.ToList
import shapeless.ops.record.{Keys, Values}

import java.io.File
import scala.concurrent.{Await, Future}
import scala.concurrent.duration.Duration

import shapeless._
import shapeless.ops.hlist._
import shapeless.ops.record._
import shapeless.record._

/**
 * Created by yz on 6/5/2021
 */
object Utils {

  val array = Array[String]("N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "N10", "N11", "N12", "N13", "N14",
    "N15", "N16", "N17", "N18", "N19", "N20", "N21", "N22", "N23", "N24", "N25", "N26", "N27", "N28", "N29", "N30",
    "N31", "N32", "CHD1", "CHD2", "CHD3", "CHD4", "CHD5", "CHD6", "CRC1", "CRC2", "CRC3", "CRC4", "CRC5", "CRC6",
    "CRC7", "CRC8", "CRC9", "CRC10", "CRC11", "CRC12", "HCC1", "HCC2", "HCC3", "HCC4", "HCC5", "HCC6", "HCC7", "HCC8",
    "HCC9", "HCC10", "HCC11", "HCC12", "HCC13", "HCC14", "HCC15", "HCC16", "HCC17", "HCC18", "HCC19", "HCC20", "HCC21",
    "PAAD1", "PAAD2", "PAAD3", "PAAD4", "PAAD5", "PAAD6", "PAAD7", "PAAD8", "PAAD9", "PAAD10", "PAAD11", "PAAD12",
    "PAAD13", "PAAD14", "WhB1", "WhB2", "WhB3", "WhB4", "WhB5")

  def getTime(startTime: Long) = {
    val endTime = System.currentTimeMillis()
    val time = (endTime - startTime) / 1000.0
    time
  }

  def isWindows = {
    System.getProperty("os.name") match {
      case x if x.contains("Windows") => true
      case _ => false
    }
  }

  def getArrayByTs[T, H <: HList](x: Seq[T])(implicit generic: LabelledGeneric.Aux[T, H],
                                             hc: Lazy[ObjectCodec[H]]) = {
    x.map { y =>
      y.myAsJson
    }
  }

  def getLinesByTs[T, R <: HList, K <: HList, V <: HList](ys: List[T])(
    implicit gen: LabelledGeneric.Aux[T, R], keys: Keys.Aux[R, K],
    values: Values.Aux[R, V],
    ktl: ToList[K, Symbol],
    vtl: ToList[V, Any]
  ) = {
    val fieldNames = keys().toList.map(_.name)
    val lines = ys.map { y =>
      gen.to(y).values.toList.map(_.toString)
    }
    fieldNames :: lines
  }

  def getJsonByTs[T, H <: HList](x: Seq[T])(implicit generic: LabelledGeneric.Aux[T, H],
                                            hc: Lazy[ObjectCodec[H]]) = {
    val array = getArrayByTs(x)
    Json.toJson(array)
  }

  def execFuture[T](f: Future[T]): T = {
    Await.result(f, Duration.Inf)
  }

  def deleteDirectory(direcotry: File) = {
    try {
      FileUtils.deleteDirectory(direcotry)
    } catch {
      case _ =>
    }
  }

  def getInfoByLines(lines: List[List[String]]) = {
    val columnNames = lines.head.map { column =>
      column.replaceAll("/", "-")
    }
    val array = lines.drop(1).map { tmpColumns =>
      val columns=tmpColumns.map(_.trimQuote)
      columnNames.zip(columns).toMap
    }
    (columnNames, array)
  }

}
